<template>
  <a-card>
    <!-- 搜索表单 -->
    <a-form class="smart-query-form" v-show="showSearch">
      <a-row class="smart-query-form-row">
        <a-form-item label="车队名称" class="smart-query-form-item">
          <a-input
            v-model:value="queryParams.teamName"
            placeholder="请输入车队名称"
            allow-clear
            @press-enter="handleQuery"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="handleQuery">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <!-- 操作按钮 -->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button
          type="primary"
          @click="handleAdd"
          v-privilege="'TeamSys:teamInfo:add'"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
        <a-button
          type="default"
          :disabled="single"
          @click="handleUpdate"
          v-privilege="'TeamSys:teamInfo:edit'"
        >
          <template #icon>
            <EditOutlined />
          </template>
          修改
        </a-button>
        <a-button
          danger
          :disabled="multiple"
          @click="handleDelete"
          v-privilege="'TeamSys:teamInfo:remove'"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          删除
        </a-button>
        <a-button
          @click="handleExport"
          v-privilege="'TeamSys:teamInfo:export'"
        >
          <template #icon>
            <DownloadOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.OFFROAD.TEAM_INFO" :refresh="getList" />
      </div>
    </a-row>

    <!-- 表格显示 -->
    <a-table
      :loading="loading"
      :data-source="teamInfoList"
      :columns="columns"
      :row-selection="rowSelection"
      :pagination="false"
      row-key="teamId"
      size="small"
      bordered
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'teamImage'">
          <a-image
            v-if="record.teamImage"
            :src="record.teamImage"
            :width="50"
            :height="50"
            style="object-fit: cover"
          />
          <span v-else>-</span>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          <span>{{ formatDate(record.createTime) }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'updateTime'">
          <span>{{ formatDate(record.updateTime) }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="handleUpdate(record)" v-privilege="'TeamSys:teamInfo:edit'">
            <template #icon>
              <EditOutlined />
            </template>
            修改
          </a-button>
          <a-button type="link" danger @click="handleDelete(record)" v-privilege="'TeamSys:teamInfo:remove'">
            <template #icon>
              <DeleteOutlined />
            </template>
            删除
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 分页 -->
    <div class="smart-query-table-page" v-show="total > 0">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="['10', '20', '50', '100']"
        :defaultPageSize="queryParams.pageSize"
        v-model:current="queryParams.pageNum"
        v-model:pageSize="queryParams.pageSize"
        :total="total"
        @change="getList"
        @showSizeChange="getList"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!-- 添加或修改车队信息对话框 -->
    <a-modal :title="title" v-model:open="open" width="500px" :mask-closable="false">
      <a-form ref="teamInfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="车队名称" name="teamName">
          <a-input v-model:value="form.teamName" placeholder="请输入车队名称" />
        </a-form-item>
        <a-form-item label="车队图片" name="teamImage">
          <FileUpload
            v-model:value="form.teamImage"
            list-type="picture-card"
            :maxUploadSize="1"
            buttonText="上传图片"
            accept="image/*"
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="cancel">取 消</a-button>
        <a-button type="primary" @click="submitForm">确 定</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup name="TeamInfo">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { listTeamInfo, getTeamInfo, delTeamInfo, addTeamInfo, updateTeamInfo } from "/@/api/offroad/TeamSys/teamInfo";
import FileUpload from "/@/components/support/file-upload/index.vue";
import TableOperator from "/@/components/support/table-operator/index.vue";
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance();

const teamInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedRowKeys = ref([]);

// 表格列定义
const columns = ref([
  {
    title: '序号',
    dataIndex: 'teamId',
    align: 'center',
    width: 80,
  },
  {
    title: '车队名称',
    dataIndex: 'teamName',
    align: 'center',
  },
  {
    title: '车队图片',
    dataIndex: 'teamImage',
    align: 'center',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    width: 180,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    align: 'center',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: 150,
    fixed: 'right',
  },
]);

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (selectedKeys, selectedRows) => {
    selectedRowKeys.value = selectedKeys;
    ids.value = selectedKeys;
    single.value = selectedKeys.length !== 1;
    multiple.value = selectedKeys.length === 0;
  }
};

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '-';
  return dayjs(dateString).format('YYYY-MM-DD');
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teamName: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询车队信息列表 */
function getList() {
  loading.value = true;
  listTeamInfo(queryParams.value).then(response => {
    teamInfoList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    teamId: null,
    teamName: null,
    teamImage: null,
    history: null,
    createTime: null,
    updateTime: null
  };
  // 重置表单验证状态
  if (proxy.$refs.teamInfoRef) {
    proxy.$refs.teamInfoRef.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    teamName: null,
  };
  handleQuery();
}



/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加车队信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _teamId = row.teamId || ids.value
  getTeamInfo(_teamId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改车队信息";
  });
}

/** 提交按钮 */
function submitForm() {
  if (proxy.$refs.teamInfoRef) {
    proxy.$refs.teamInfoRef.validate().then(() => {
      if (form.value.teamId != null) {
        updateTeamInfo(form.value).then(() => {
          message.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTeamInfo(form.value).then(() => {
          message.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }).catch(() => {
      console.log('表单验证失败');
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _teamIds = row?.teamId || ids.value;
  Modal.confirm({
    title: '确认删除',
    content: `是否确认删除车队信息编号为"${_teamIds}"的数据项？`,
    onOk() {
      return delTeamInfo(_teamIds).then(() => {
        getList();
        message.success("删除成功");
      });
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  // 这里需要根据实际的导出API进行调整
  console.log('导出功能需要根据实际API实现');
  message.info('导出功能需要根据实际API实现');
}

getList();
</script>
